package com.xb.loan.usercenter.user.user.service.impl;

import com.xb.loan.log.exception.BizException;
import com.xb.loan.usercenter.service.user.IUserThirdCardService;
import com.xb.loan.usercenter.service.user.bean.UserThirdCardVO;
import com.xb.loan.usercenter.user.user.dao.UserInfoDao;
import com.xb.loan.usercenter.user.user.dao.UserThirdCardDao;
import com.xb.loan.usercenter.user.user.dao.bean.UserThirdCard;
import com.xb.loan.util.common.ObjectOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户第三方卡逻辑
 */
@Service("userThirdCardService")
public class UserThirdCardServiceImpl implements IUserThirdCardService {

    @Autowired
    UserThirdCardDao userThirdCardDao;
    
    @Autowired
    UserInfoDao userInfoDao;
    
    @Autowired  //①  注入上下文  
    private ApplicationContext context;  
    
    private UserThirdCardServiceImpl proxySelf; //②  表示代理对象，不是目标对象
    
    @PostConstruct  //③ 初始化方法
    private void setSelf() {
        //从上下文获取代理对象（如果通过proxtSelf=this是不对的，this是目标对象）  
        //此种方法不适合于prototype Bean，因为每次getBean返回一个新的Bean  
        proxySelf = (UserThirdCardServiceImpl) context.getBean(IUserThirdCardService.class);   
    }

    @Override
    public int updateByPrimaryKeySelective(UserThirdCardVO userThirdCardVO, String userId, String password) throws BizException {
        UserThirdCard userThirdCard = ObjectOperation.convertByClasses(userThirdCardVO, UserThirdCard.class);
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        map.put("pwd", password);
        return proxySelf.updateHttpTransaction(userThirdCard, map);
    }
    
    /**
     * 用户注册，保存数据
     * @param userThirdCard         用户实例
     * @param map         现金帐户实例
     * 2015年9月1日 by wuqinglong
     */
    @Transactional
    public int updateHttpTransaction(UserThirdCard userThirdCard, Map<String, Object> map)  throws BizException{
        int flag = userThirdCardDao.updateByPrimaryKeySelective(userThirdCard);
        if(flag > 0){
            flag = userInfoDao.updateUserInfo(map);
        }
        return flag;
    }
    @Override
    public UserThirdCardVO query(String cardNo) {
        UserThirdCard userThirdCard = userThirdCardDao.query(cardNo);
        if(userThirdCard == null ){
            return null;
        }
        UserThirdCardVO userThirdCardVO = (UserThirdCardVO) ObjectOperation.convertByClasses(userThirdCard, UserThirdCardVO.class);
        return userThirdCardVO;
    }
}
